<?php
/**
 * Function:
 * Description:
 * Abo 2019/1/14 19:19
 * Email: abo2013@foxmail.com
 */

namespace Abo\Fasterapi\V0\Controllers\Rwapi;

use Abo\Generalutil\V1\Exceptions\ApiException;
use Abo\Generalutil\V1\Utils\ResponseUtil;
use App\Http\Controllers\Controller;

class RwClientController extends Controller
{
    const RWAPI_DOMAIN = 'http://mobile.local.aidalan.com/api/';
    const MOBILE_AIDALAN_SALT = 'mobile.aidalan.com_RwApi_Y6XQV4pa3k09';

    protected $urlParam = [], $ruleMsgs = [];
    private $cacheKey,$tableName = '';
    private $tableColumns = [ '*' ]; // 列表/详情 查询字段

    protected function __construct( string $tableName, array $tableColumns, string $cacheKey = '', array $ruleMsgs = [] )
    {
        if ( !$tableName || !$tableColumns ) {
            throw new ApiException( '程序配置项缺失,请及时补充', 604  );
        }

        $this->tableName = $tableName;
        $this->tableColumns = $tableColumns;
        $this->urlParam = $_REQUEST;
        $cacheKey && $this->cacheKey = $cacheKey;
        $ruleMsgs && $this->ruleMsgs = $ruleMsgs;
    }

    public function update($id)
    {
        $this->validator( $this->ruleMsgs[ 'rule' ], [] );

        $ret2Request = $this->commonUpdate( $_POST, $id );
        return $this->formatReturn( $ret2Request );
    }

    public function store()
    {
        $this->validator( $this->ruleMsgs[ 'rule' ], [] );

        $ret2Request = $this->commonInsert( $_POST );
        return $this->formatReturn( $ret2Request );
    }

    public function destroy( int $id, string $column = 'id' )
    {
        $ret2Request = $this->commonDestroy( $id, $column );
        return $this->formatReturn( $ret2Request, true );
    }

    public function refresh( $key )
    {
        if ( !$key ){ return false; }

        $form_params = [
            'table' => $this->tableName,
            'data' => [],
            'key' => $key,
            'sign' => $this->getSign( [] ),
        ];
        $ret2RequestJson = makeRequest(
            'POST',
            self::RWAPI_DOMAIN.'rwapi/refresh',
            json_encode($form_params), "application/json", 5, false
        );

        return $ret2RequestJson;
    }

    /** 列表 */
    public function commonList( array $where = [ 'and' => [], 'like' => [] ] )
    {
        $ret2Request = $this->baseApiRequest( $this->tableColumns, $where );

        $data = [
            'data' => $ret2Request[ 'content' ],
            'nums' => $ret2Request[ 'nums' ],
            'pages' => $ret2Request[ 'pages' ],
        ];

        return $data;
    }

    /** 详情 */
    public function commonDetail(  int $id )
    {
        $ret2Return = array_combine(
            $this->tableColumns,
            array_fill ( 0 , count($this->tableColumns), '' )
        );

        if ( !$id ) { return $ret2Return; }

        $detail = $this->baseApiRequest( $this->tableColumns, [ 'and' => [ 'id' => $id ], 'like' => [] ] );
        return $ret2Return = current( $detail[ 'content' ] );
    }

    /** 添加 */
    public function commonInsert( array $data )
    {
        $data = $this->filterNoTableColumn( $data );

        $form_params = [
            'table' => $this->tableName,
            'data' => $data,
            'sign' => $this->getSign( $data ),
        ];
        $ret2RequestJson = makeRequest(
            'POST',
            self::RWAPI_DOMAIN.'rwapi/add?XDEBUG_SESSION_START=19691',
            json_encode($form_params), "application/json", 5, false
        );

        $ret2Request = json_decode($ret2RequestJson['result'], true);
        if ( !$ret2Request ) { $ret2Request = [ 'data' => [], 'msg' => '操作异常请返回' ]; }

        $this->refresh( $this->cacheKey );
        return $ret2Request;
    }

    /** 更新 */
    public function commonUpdate( array $data, int $id )
    {
        $data = $this->filterNoTableColumn( $data );

        $form_params = [
            'table' => $this->tableName,
            'data' => $data,
            'id' => $id,
            'sign' => $this->getSign( $data ),
        ];
        $ret2RequestJson = makeRequest(
            'POST',
            self::RWAPI_DOMAIN.'rwapi/save?XDEBUG_SESSION_START=19691',
            json_encode($form_params), "application/json", 5, false
        );

        $ret2Request = json_decode($ret2RequestJson['result'], true);
        if ( !$ret2Request ) { $ret2Request = [ 'data' => [] ]; }

        $this->refresh( $this->cacheKey );
        return $ret2Request;
    }

    /** 删除 */
    public function commonDestroy( int $id, string $column = 'id' )
    {
        $form_params = [
            'table' => $this->tableName,
            'data' => [],
            'id' => $id,
            'column' => $column,
            'sign' => $this->getSign( [] ),
        ];
        $ret2RequestJson = makeRequest(
            'POST',
            self::RWAPI_DOMAIN.'rwapi/del?XDEBUG_SESSION_START=19691',
            json_encode($form_params), "application/json", 5, false
        );

        $ret2Request = json_decode($ret2RequestJson['result'], true);
        if ( !$ret2Request ) { $ret2Request = [ 'data' => [], 'msg' => '操作异常请返回' ]; }

        $this->refresh( $this->cacheKey );
        return $ret2Request;
    }


    /** 数据后台,盐值产生方法 @param array $data 请求参数 */
    protected function getSign( array $params )
    {
        ksort($params);
        $sign_str = '';
        foreach ($params as $key => $value) {
            $temValue = is_array( $value ) ? implode( ',', $value ) : $value;
            $sign_str .= $key . '=' . $temValue . '&';
        }

        $sign_str = substr($sign_str, 0, -1);
        $sign_str .= self::MOBILE_AIDALAN_SALT ?? '';
        $sign_str = md5($sign_str);
        return $sign_str;
    }

    public function formatReturn( array $ret2Request, bool $isPage = false )
    {
        if ( $ret2Request[ 'ret' ] ) {
            if ( $isPage ) { return app('redirect')->back( 302, [], false); } // 页面返回
            return ResponseUtil::success()->with( $ret2Request )->json(); // 默认json返回
        }else{
            return ResponseUtil::error()->message( $ret2Request[ 'msg' ] )->json();
        }
    }

    public function setTableName( string $tableName )
    {
        $this->tableName = $tableName;
    }

    /** 过滤非数据表字段 todo 伪数据表字段过滤 */
    private function filterNoTableColumn( array $data )
    {
        if ( !$data ) { return []; }

        $ret2Return = [];
        foreach ( $data as $k2Data => $v2Data ) {
            if ( 0 === strpos( $k2Data, '_' ) ) { continue; }
            $ret2Return[ $k2Data ] = $v2Data;
        }

        return $ret2Return;
    }

    private function baseApiRequest( array $columns, array $where = [ 'and' => [], 'like' => [] ] )
    {
        $form_params = [
            'table' => $this->tableName,
            'data' => $columns,
            'condition' => $where,
            'page' => isset( $_REQUEST['page'] )?$_REQUEST['page']: 1,
            'pageSize' => isset( $_REQUEST['pageNum'] )?$_REQUEST['pageNum']:100,
            'orderBy' => 'id',
            'sign' => $this->getSign( $columns ),
        ];
        $ret2RequestJson = makeRequest(
            'POST',
            self::RWAPI_DOMAIN.'rwapi/list?XDEBUG_SESSION_START=19691',
            json_encode($form_params), "application/json", 5, false
        );

        $ret2Request = json_decode($ret2RequestJson['result'], true);
        if ( !$ret2Request ) { return [ 'content' => [] ]; }

        $ret2Request[ 'pages' ] = ceil( ($ret2Request[ 'nums' ]/$form_params[ 'pageSize' ]) );

        return $ret2Request;
    }

    /**
     * 验证参数合法性
     * @param array $form_rules 参数验证规则
     */
    protected function validator($formRules, $msg){
        $VaildParam = new VaildParam();
        return $VaildParam->validator( $formRules, $msg );
    }
}